import 'package:flutter/material.dart';
import '../../models/post_model.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import '../../utils/cached_image_widget.dart';
import 'package:base_flutter/src/network/network_exception.dart';
import '../order/order_confirm_page.dart';

/// 服务商品详情页面
/// 专门用于展示服务商品的详细信息，包括价格、服务类型、联系方式等
class ServiceDetailPage extends StatefulWidget {
  final PostModel post;

  const ServiceDetailPage({
    super.key,
    required this.post,
  });

  @override
  State<ServiceDetailPage> createState() => _ServiceDetailPageState();
}

class _ServiceDetailPageState extends State<ServiceDetailPage> {
  Map<String, dynamic>? _serviceDetail;
  bool _isLoading = true;
  String? _error;
  bool _isFavorited = false;

  @override
  void initState() {
    super.initState();
    _loadServiceDetail();
  }

  /// 加载服务商品详情
  Future<void> _loadServiceDetail() async {
    try {
      setState(() {
        _isLoading = true;
        _error = null;
      });

      final result = await ApiService().getServiceDetail(widget.post.id);
      
      setState(() {
        _serviceDetail = result;
        _isLoading = false;
      });

      Logger.d('SERVICE_DETAIL', '服务商品详情加载成功');
    } catch (e) {
      Logger.e('SERVICE_DETAIL', '服务商品详情加载失败: $e');
      setState(() {
        _error = e is NetworkException ? e.message : '加载失败';
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('商品详情'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
        actions: [
          IconButton(
            icon: Icon(
              _isFavorited ? Icons.favorite : Icons.favorite_border,
              color: _isFavorited ? Colors.red : Colors.grey,
            ),
            onPressed: _handleFavorite,
          ),
          IconButton(
            icon: const Icon(Icons.share),
            onPressed: _handleShare,
          ),
        ],
      ),
      body: _buildBody(),
      bottomNavigationBar: _buildBottomBar(),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (_error != null) {
      // 判断是否是商品不存在的错误
      final bool isNotFound = _error!.contains('不存在') || _error!.contains('404');
      
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              isNotFound ? Icons.remove_shopping_cart : Icons.error_outline,
              size: 64,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              isNotFound ? '该商品已下架或不存在' : _error!,
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 8),
            if (isNotFound)
              Text(
                '商品可能已被删除或已售罄',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[500],
                ),
              ),
            const SizedBox(height: 24),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                OutlinedButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('返回'),
                ),
                if (!isNotFound) ...[
                  const SizedBox(width: 16),
                  ElevatedButton(
                    onPressed: _loadServiceDetail,
                    child: const Text('重试'),
                  ),
                ],
              ],
            ),
          ],
        ),
      );
    }

    if (_serviceDetail == null) {
      return const Center(
        child: Text('商品信息不存在'),
      );
    }

    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildHeader(),
          _buildCategorySection(),
          _buildDescription(),
          const SizedBox(height: 80), // 为底部按钮留空间
        ],
      ),
    );
  }

  /// 构建商品类别（使用后端返回的 serviceInfo.type）
  Widget _buildCategorySection() {
    final serviceInfo = _serviceDetail!['serviceInfo'] as Map<String, dynamic>?;
    final category = serviceInfo != null ? (serviceInfo['type'] as String? ?? '未分类') : '未分类';

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
            decoration: BoxDecoration(
              color: Colors.blue.withOpacity(0.08),
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: Colors.blue.withOpacity(0.25)),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Icon(Icons.local_offer, size: 16, color: Colors.blue),
                const SizedBox(width: 6),
                Text(
                  category,
                  style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Colors.blue),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建头部图片区域
  Widget _buildHeader() {
    final mediaInfo = _serviceDetail!['mediaInfo'] as Map<String, dynamic>?;
    final coverUrl = mediaInfo?['coverUrl'] as String?;
    final images = mediaInfo?['images'] as List<dynamic>?;

    return Container(
      height: 250,
      width: double.infinity,
      child: coverUrl != null && coverUrl.isNotEmpty
          ? CachedImageWidget(
              imageUrl: coverUrl,
              width: double.infinity,
              height: 250,
              fit: BoxFit.cover,
              imageType: '商品详情封面',
              errorWidget: Container(
                color: Colors.grey[200],
                child: const Icon(Icons.shopping_bag, size: 100, color: Colors.grey),
              ),
            )
          : Container(
              color: Colors.grey[200],
              child: const Icon(Icons.shopping_bag, size: 100, color: Colors.grey),
            ),
    );
  }

  /// 构建价格信息区域
  Widget _buildPriceSection() {
    final priceInfo = _serviceDetail!['priceInfo'] as Map<String, dynamic>?;
    final title = _serviceDetail!['title'] as String? ?? '未知商品';

    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: const TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          if (priceInfo != null) ...[
            Text(
              priceInfo['displayText'] ?? '价格面议',
              style: const TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
                color: Colors.red,
              ),
            ),
          ],
        ],
      ),
    );
  }

  // 旧的服务信息卡片暂时移除，按需求仅展示类别与描述

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              label,
              style: TextStyle(
                color: Colors.grey[600],
                fontSize: 14,
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建商品描述
  Widget _buildDescription() {
    final description = _serviceDetail!['description'] as String?;

    if (description == null || description.isEmpty) {
      return const SizedBox.shrink();
    }

    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '商品描述',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 12),
          Text(
            description,
            style: const TextStyle(
              fontSize: 14,
              height: 1.5,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建发布者信息
  Widget _buildPublisherInfo() {
    final publisherInfo = _serviceDetail!['publisherInfo'] as Map<String, dynamic>?;
    final timeInfo = _serviceDetail!['timeInfo'] as Map<String, dynamic>?;

    if (publisherInfo == null) return const SizedBox.shrink();

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '商家信息',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              CachedAvatarWidget(
                avatarUrl: publisherInfo['avatar'] as String?,
                size: 48,
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      publisherInfo['nickname'] ?? '未知商家',
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    if (timeInfo != null) ...[
                      Text(
                        '发布于 ${timeInfo['displayTime'] ?? '未知时间'}',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey[600],
                        ),
                      ),
                    ],
                  ],
                ),
              ),
              OutlinedButton(
                onPressed: _handleContact,
                child: const Text('联系商家'),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建互动统计
  Widget _buildInteractionStats() {
    final interactionInfo = _serviceDetail!['interactionInfo'] as Map<String, dynamic>?;

    if (interactionInfo == null) return const SizedBox.shrink();

    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildStatItem('浏览', interactionInfo['viewsCount'] ?? 0),
          _buildStatItem('点赞', interactionInfo['likesCount'] ?? 0),
          _buildStatItem('评论', interactionInfo['commentsCount'] ?? 0),
          _buildStatItem('分享', interactionInfo['sharesCount'] ?? 0),
        ],
      ),
    );
  }

  Widget _buildStatItem(String label, int count) {
    return Column(
      children: [
        Text(
          count.toString(),
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }

  /// 构建底部操作栏
  Widget _buildBottomBar() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.2),
            spreadRadius: 1,
            blurRadius: 3,
            offset: const Offset(0, -1),
          ),
        ],
      ),
      child: SizedBox(
        width: double.infinity,
        child: ElevatedButton(
          onPressed: _handleBuy,
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.blue,
            padding: const EdgeInsets.symmetric(vertical: 14),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
          ),
          child: const Text(
            '立即购买',
            style: TextStyle(
              fontSize: 16,
              color: Colors.white,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
      ),
    );
  }

  /// 处理购买
  void _handleBuy() async {
    if (_serviceDetail == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('商品信息加载中，请稍候')),
      );
      return;
    }

    try {
      // 跳转到订单确认页面
      final result = await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => OrderConfirmPage(
            serviceProductId: int.parse(widget.post.id),
            serviceDetail: _serviceDetail!,
          ),
        ),
      );

      // 如果支付成功，刷新页面
      if (result != null && result['success'] == true) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('购买成功！'),
            backgroundColor: Colors.green,
          ),
        );
      }
    } catch (e) {
      Logger.e('SERVICE_DETAIL', '跳转购买页面失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('打开购买页面失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 处理收藏操作
  void _handleFavorite() async {
    try {
      setState(() {
        _isFavorited = !_isFavorited;
      });

      await ApiService().favoriteService(widget.post.id, _isFavorited);
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(_isFavorited ? '已收藏' : '已取消收藏'),
          duration: const Duration(seconds: 1),
        ),
      );
    } catch (e) {
      setState(() {
        _isFavorited = !_isFavorited;
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('操作失败: ${e is NetworkException ? e.message : '网络错误'}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 处理分享操作
  void _handleShare() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('分享功能开发中')),
    );
  }

  /// 处理联系商家
  void _handleContact() {
    final contactInfo = _serviceDetail!['contactInfo'] as Map<String, dynamic>?;
    final contact = contactInfo?['info'] as String?;

    if (contact != null && contact.isNotEmpty) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('联系方式'),
          content: Text(contact),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('确定'),
            ),
          ],
        ),
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('暂无联系方式')),
      );
    }
  }

  /// 处理咨询操作
  void _handleInquire() async {
    try {
      await ApiService().inquireService(widget.post.id);
      
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('咨询记录成功，商家将尽快回复')),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('咨询失败: ${e is NetworkException ? e.message : '网络错误'}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 处理预约操作
  void _handleBook() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('预约服务'),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              decoration: InputDecoration(
                labelText: '您的姓名',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 16),
            TextField(
              decoration: InputDecoration(
                labelText: '联系电话',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 16),
            TextField(
              decoration: InputDecoration(
                labelText: '预约时间',
                border: OutlineInputBorder(),
                hintText: '请输入希望的服务时间',
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('预约提交成功，商家将联系您确认')),
              );
            },
            child: const Text('确认预约'),
          ),
        ],
      ),
    );
  }
}
